# coding=utf-8
'''
Created on 31 août 2012

@author: patrick.merheb
'''

from yahoo import ystockquote
from datetime import datetime
import anydbm
import pickle
import smtplib
from email.mime.text import MIMEText
    

    
def readLastPrice(symbol):
    db = anydbm.open('prices.db', 'c')
    if symbol in db:
        (lastPrice,lastStop) = pickle.loads(db[symbol]) 
        db.close()
        return (float(lastPrice),float(lastStop))
    else :
        db.close()
        return (None,None)

def writeLast(symbol, currentPrice,currentStop):
    fout = open("stock-history.txt",'a')  
    fout.write("%s;%s;%s;%s\n"%(datetime.now(),symbol,currentPrice,currentStop))
    db = anydbm.open('prices.db', 'c')
    db[symbol] = pickle.dumps((str(currentPrice),str(currentStop)))
    db.close()
    
def sendAlertMail(symbol):
    me = "patrick.merheb@gmail.com"
    msg = MIMEText("SELL Signal : %s\r\n"%symbol)
    msg['Subject'] = 'Portfolio Monitoring Alert'
    msg['From'] = me
    msg['To'] = me
    server = smtplib.SMTP("smtp.canl.nc")
    server.login("patrick.merheb@canl.nc", "password41425949")
    server.set_debuglevel(1)
    server.sendmail(me, me, msg.as_string())
    server.quit()


## Methode de contrôle sur symbol    
def check(symbol,stopPercent):
    (lastPrice,lastStop) = readLastPrice(symbol)
    currentPrice =  ystockquote.get_price(symbol)
    if lastStop is None:
        currentStop = float(currentPrice) * (1-stopPercent)
    
    if (lastPrice is None):
        lastPrice = currentPrice;
            
    uptick = (currentPrice >= lastPrice)
    #update the trailing stop 
    if uptick == True :
        currentStop =  float(currentPrice) * (1-stopPercent)
    else :
        currentStop = lastStop
    # See if we broke the trailing stop 
    if (currentPrice < currentStop):
        print "%s breaks the stop : SELL SIGNAL" %(symbol)
        #Envoyer un mail  
        sendAlertMail(symbol)    
    ##Persist current price and stop 
    writeLast(symbol,currentPrice,currentStop)
        
if __name__ == '__main__':
    #print "LBPAM Action France C :"  + ystockquote.get_price('FR0000003592')
    #print "LBPAM Actions Midcap C :" + ystockquote.get_price('FR0000934325.PA')
#    print "ADP :" + ystockquote.get_price('ADP.PA')
#    print "EADS :" + ystockquote.get_price('EAD.PA')
#    print "SANOFI :" + ystockquote.get_price('SAN.PA')
#    print "NATIXIS :" + ystockquote.get_price('KN.PA')
    check('ADP.PA', 0.05)## ADP
    check('EAD.PA', 0.05) ##EADS
    check('SAN.PA', 0.05)## Sanofi Avantis
    check('KN.PA', 0.05)##Natixis         
    

    
    
        